<template>
    <div class="header c-b-b c-f-h c-f-between-center c-p-h-m">
        <h2 class="brand c-m-0">
            <a href="/">
                <img src="@/assets/images/aosv.svg" />
                <span>AOSV</span>
            </a>
        </h2>
        <AInputSelect color="success" :getTextFunc="(a: MenuItem) => a.name" placeholder="搜索" @itemClick="methods.itemClick" />
    </div>
    <div class="main">
        <AScrollable :scrollbarDraggable="true">
            <AMenu class="app-menu c-b-r c-f-shrink-0" :items="state.menuItems" :getIsFolderFunc="(a: MenuItem) => !!a.files" :getItemsFunc="(a: MenuItem) => a.files!" @file-click="methods.itemClick" ref="menuRef">
            </AMenu>
        </AScrollable>
        <AScrollable :scrollbarDraggable="true">
            <div class="content">
                <router-view></router-view>
            </div>
        </AScrollable>
    </div>
</template>

<style lang="scss" scoped>
.header {
    box-sizing: border-box;

    .brand {
        a {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #000;

            img {
                width: 48px;
                height: 48px;
            }
        }
    }
}

.main {
    display: grid;
    grid-template-columns: 300px 1fr;
    overflow: hidden;

    .content {
        padding: 15px;
        flex-grow: 1;
        overflow: auto;
    }
}
</style>

<script setup lang="ts">
import { AInputSelect, AScrollable, AMenu } from 'aosv'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface MenuItem {
    name: string
    path?: string
    files?: MenuItem[]
}
const state = reactive({
    menuItems: [
        {
            name: '组件',
            files: [
                { name: 'AButton', path: '/components/AButton' },
                { name: 'AAlert', path: '/components/AAlert' },
                { name: 'ABadge', path: '/components/ABadge' },
                { name: 'AInputRichText', path: '/components/AInputRichText' },
            ]
        }
    ] as MenuItem[]
})

const router = useRouter()
const route = useRoute()
const menuRef = ref()
onMounted(() => {
    setTimeout(() => {
        methods.findAndOpenCurrentFolder()
    }, 0)//过0秒再设置菜单，因为mounted时，路由还是/
})
const methods = {
    itemClick(item: MenuItem) {
        if (item.path) {
            router.push(item.path)
        }
    },
    findAndOpenCurrentFolder() {
        let currentPath = route.path
        let toCheckList = [...state.menuItems]
        while (toCheckList.length) {
            let item = toCheckList.shift()!
            if (currentPath == item.path) {
                menuRef.value.activeItem(item)
                return
            }
            if (item.files) {
                toCheckList.push(...item.files)
            }
        }
    },
}
</script>